package org.ycx.upms.client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by 杨 on 2017-06-26.
 */
@Service
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    //通过2中方式实现redis,或者map对象
    @Autowired
    private ISecurityMetaData data;


    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //object 中包含用户请求的request 信息
        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest ();
        List<String> auths = data.getGrantAuthority (request);
        List<ConfigAttribute> configs = new ArrayList<ConfigAttribute> ();
        if(auths!=null){
            for (String auth : auths) {
                configs.add (new SecurityConfig (auth));
            }
        }
        return configs;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
//        方法如果返回了所有定义的权限资源，Spring Security会在启动时校验每个ConfigAttribute是否配置正确，不需要校验直接返回null。
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        //方法返回类对象是否支持校验，web项目一般使用FilterInvocation来判断，或者直接返回true。
        return true;
    }
}
